
#include "param.h"

uint8_t load_param(uint32_t* src, uint32_t* dst, uint8_t len){
	uint32_t* pm = (uint32_t*)PARAM_START_ADDRESS;
	uint32_t i = 0;
	if( (void*)0==src || (void*)0==dst || 0==len) return 0;
	
	if( (uint32_t)0xAA==*((uint32_t*)(PARAM_START_CRC)) && (uint32_t)0x55==*((uint32_t*)(PARAM_START_CRC+4)) ){
		for( i=0; i<len; ++i ){
			dst[i] = (uint32_t)*pm;
			++pm;
		}
	}else{
		if(0==save_param(src, len)) return 0;
		load_param(src, dst, len);
	}
	
	return 1;
}

uint8_t save_param(uint32_t* params, uint32_t len){
	uint32_t i;
	FLASH_EraseInitTypeDef eraseinit;
	uint32_t pageerror;
	uint32_t add = PARAM_START_ADDRESS;
	
	if((void*)0==params ) return 0;
	
	eraseinit.NbPages = 1;
	eraseinit.PageAddress = PARAM_START_ADDRESS;
	eraseinit.TypeErase = FLASH_TYPEERASE_PAGES;
	eraseinit.Banks = FLASH_BANK_1;
	
	if( HAL_OK!=FLASH_WaitForLastOperation(100) ) return 0;
	
	CLOSE_IRP1();
		
	if( HAL_OK!=HAL_FLASH_Unlock() ){
		HAL_FLASH_Lock();
		OPEN_IRP1();
		return 0;
	}
	
	if( HAL_OK!=HAL_FLASHEx_Erase(&eraseinit, &pageerror) ){
		HAL_FLASH_Lock();
		OPEN_IRP1();
		return 0;
	}
	
	for( i=0; i<len; ++i ){
		if( HAL_OK!=HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, add, (uint64_t)params[i]) ){
			HAL_FLASH_Lock();
			OPEN_IRP1();
			return 0;
		}
		if( params[i]!=*((uint32_t*)add) ){
			HAL_FLASH_Lock();
			OPEN_IRP1();
			return 0;
		}
		add += 4;
	}	
	
	if( HAL_OK!=HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, PARAM_START_CRC, 0xaa) ){
			HAL_FLASH_Lock();
		  OPEN_IRP1();
			return 0;
	}
	
	if( 0xaa!=*((uint32_t*)PARAM_START_CRC) ){
			HAL_FLASH_Lock();
		  OPEN_IRP1();
			return 0;
	}
	
	if( HAL_OK!=HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, PARAM_START_CRC+4, 0x55) ){
		HAL_FLASH_Lock();
		OPEN_IRP1();
		return 0;
	}
	
	if( 0x55!=*((uint32_t*)(PARAM_START_CRC+4)) ){
			HAL_FLASH_Lock();
		  OPEN_IRP1();
			return 0;
	}
	
	HAL_FLASH_Lock();	
	
	OPEN_IRP1();
	
	return 1;
}

